import { _decorator, Component, director, Node, Prefab } from 'cc';
import { Constant } from './Constant';
import { ResUtil } from './ResUtil';
import { BattleContext } from './BattleContext';
import { PoolManager } from './PoolManager';
const { ccclass, property } = _decorator;

@ccclass('Globals')
export class Globals extends Component {

    static prefabs:Record<string, Prefab> = {};

    // CONFIG
    // DATA

    protected onLoad(): void {
        director.addPersistRootNode(this.node);
    }

    start() {

    }

    update(deltaTime: number) {
        
    }

    static init() {
        const keys = Object.keys(Constant.PrefabUrl)
        const promises:Promise<any>[] = [];
        console.log(keys)
        keys.forEach(key=> {
            const url = Constant.PrefabUrl[key];
            console.log('加载了哪些url资源', url)
            const p = ResUtil.loadPrefab(url).then((pf:Prefab) => {
                // BattleContext.prefabs[url] = pf;
                Globals.prefabs[url] = pf;
            })
            promises.push(p);
        });
        return Promise.all(promises);
    }

    /**
     * 根据名称和父节点从节点池中获取节点
     * @param name 节点的名称，用于从预设字典中查找对应的预设
     * @param parent 节点的父节点，用于设置新获取节点的父节点
     * @returns 返回从节点池中获取的节点
     */
    static getNode(name: string, parent: Node) {
        // 从节点池中根据名称获取对应的节点实例
        const node = PoolManager.instance.get(this.prefabs[name])
        // 设置节点的父节点
        node.parent = parent;
        // 返回获取的节点
        return node;
    }

    static putNode(node: Node) {
        PoolManager.instance.put(node);
    }

}


